<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" effect="dark"> </el-alert>
      <!-- 进度条 -->
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        label-width="80px"
        label-position="top"
        :rules="addFormRules"
        :model="addForm"
        ref="addFormRef"
      >
        <el-tabs
          v-model="active"
          tab-position="left"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id'
                }"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数(动态)" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableDate"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item1"
                  :key="index1"
                  v-for="(item1, index1) in item.attr_vals1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性(静态)" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableDate"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="uploadPic"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="PreviewDialogVisible"
      width="50%"
    >
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'Add',
  theme: 'snow', // 主题
  data () {
    return {
      active: 0,
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        pics: [], // 上传图片的临时路径
        goods_introduce: 'abc',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        goods_price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入数量', trigger: 'blur' }]

      },
      cateList: [],
      manyTableDate: [],
      onlyTableDate: [],
      // uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      uploadURL: 'http://www.linweisong.top:8888/api/private/v1/upload',
      // uploadURL: 'https://www.linweisong.top:9999/api/private/v1/upload',
      fileList: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '', // 图片的路径
      PreviewDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败！')
      this.cateList = res.data
      // console.log(this.cateList)
    },
    async handleChange () {
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = []
        this.$message.error('请选择三级分类！')
      }
      // 动态参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
      res.data.forEach((item) => {
        if (item.attr_vals.trim().length === 0) {
          item.attr_vals = item.attr_vals1 = []
        } else {
          item.attr_vals = item.attr_vals1 = item.attr_vals.split(' ')
        }
      })
      this.manyTableDate = res.data
      // 静态参数
      const { data: res1 } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
      if (res1.meta.status !== 200) return this.$message.error('获取数据失败！')
      this.onlyTableDate = res1.data
      // console.log(this.onlyTableDate)
    },
    beforeLeave (to, from) {
      if (from === '0' && this.addForm.goods_cat.length < 3) {
        this.$message.error('请选择三级分类！')
        return false
      }
    },
    async tabClick () {
      // 获取商品参数（动态）
      if (this.active === '1') {

        // console.log(this.manyTableDate)
        // 获取商品属性（静态）
      } else if (this.active === '2') {

      } else if (this.active === '3') {

      } else {

      }
    },
    // 图片预览
    handlePreview (res) {
      this.previewPath = res.response.data.url
      this.PreviewDialogVisible = true
    },
    // 图片移除
    handleRemove (res) {
      // console.log(res)
      var index = this.addForm.pics.findIndex(item => item.pic === res.response.data.tmp_path)
      this.addForm.pics.splice(index, 1)// 找到符合的索引，然后根据索引移除
    },
    // 上传成功的钩子
    handleSuccess (res) {
      // console.log(res)
      const obj = {
        pic: res.data.tmp_path
      }
      this.addForm.pics.push(obj)
      // console.log(this.addForm.pics)
    },
    add () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          /* eslint-disable */
          this.$message.error('请填写合法的数据项')
          return
        }
        // 执行添加的业务逻辑
        var form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数，静态属性
        form.attrs = []
        this.manyTableDate.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })

        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })

    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  }
}
</script>

<style scoped lang="less">
.el-steps {
  margin-top: 20px;
  /deep/ .el-step__title,
  .el-step__icon-inner {
    font-size: 12px !important;
  }
}
.previewImg {
  width: 100%;
}
/deep/.ql-editor {
  height: 300px;
}
.quill-editor {
  margin-bottom: 20px;
}
</style>
